<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: qupen
  Date: 2016/9/18
  Time: 19:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:include page="../../include/head.jsp">
    <jsp:param name="title" value="机床元数据管理"/>
</jsp:include>

<jsp:include page="../../include/tenant_header.jsp"/>

<jsp:include page="../../include/tenant_sidebar.jsp"/>

<div class="content-wrapper content-wrapper-bg">
    <section class="content-header">
        <h4 style="display: inline;" class="page-title"><spring:message code="label.tenant.idle.template"/></h4>
        <a id="setting" class="btn btn-add" data-toggle="modal" data-target="#myModal"
           style="margin-left:84px;cursor: pointer;">
            <i class="fa fa-plus" style="margin-right: 3px"></i><spring:message
                code="label.tenant.set.availability.formula"/>
        </a>
    </section>
    <section class="content" style="min-height: 10px">
        <div class="box box-primary table-header-line" style="margin-bottom: 0">
            <div class="box-body" style="padding:0 0 10px 0 ">
                <div class="form-horizontal">
                    <table style="width: 100%;" id="IDLE_TABLE">
                        <thead>
                        <tr>
                            <td class="table-header" style="width: 30%;"><spring:message
                                    code="label.tenant.idleReason"/></td>
                            <td class="table-header" style="width: 35%;"><spring:message
                                    code="label.tenant.create.description"/></td>
                            <td class="table-header" style="width: 15%;"><spring:message
                                    code="label.tenant.check.event"/></td>
                            <td class="table-header" style="width: 20%;border-right: none"><spring:message
                                    code="label.operation"/></td>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <div style="width: 100%;padding-top:10px;text-align: center;">
                        <a id="add_idle" class="hollow-button-green" data-id="IDLE_TABLE"
                           href="javascript:;"><spring:message code="label.Add"/></a><!--
                        --><a class="hollow-button-green hidden show-or-hidden" data-id="IDLE_TABLE" href="javascript:;"
                              onclick="saveIDLE(this,'IDLEReason')"><spring:message code="label.user.save"/></a>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <section class="content-header">
        <h4 class="page-title"><spring:message code="label.tenant.fault.template"/></h4>
    </section>
    <section class="content" style="min-height: 10px">
        <div class="box box-primary table-header-line" style="margin-bottom: 0">
            <div class="box-body" style="padding:0 0 10px 0 ">
                <div class="form-horizontal">
                    <table style="width: 100%;" id="FaultType_TABLE">
                        <thead>
                        <tr>
                            <td class="table-header" style="width: 30%;"><spring:message
                                    code="label.tenant.fault.type"/></td>
                            <td class="table-header" style="width: 50%;"><spring:message
                                    code="label.tenant.create.description"/></td>
                            <td class="table-header" style="width: 20%;border-right: none"><spring:message
                                    code="label.operation"/></td>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <div style="width: 100%;padding-top:10px;text-align: center;">
                        <a id="add_faultType" class="hollow-button-green" data-id="FaultType_TABLE" href="javascript:;"><spring:message
                                code="label.Add"/></a><!--
                        --><a class="hollow-button-green hidden show-or-hidden" data-id="FaultType_TABLE"
                              href="javascript:;"
                              onclick="saveFaultType(this,'FaultTypeReason')"><spring:message code="label.save"/></a>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <section class="content-header">
        <h4 class="page-title"><spring:message code="label.tenant.device.typeOrModel.template"/></h4>
    </section>
    <section class="content" style="min-height: 10px;padding-bottom: 30px">
        <div class="box box-primary table-header-line" style="margin-bottom: 0">
            <div class="box-body" style="padding:0 0 10px 0 ">
                <div class="form-horizontal">
                    <table style="width: 100%;" id="MachineNumber_TABLE">
                        <thead>
                        <tr>
                            <td class="table-header" style="width: 15%;"><spring:message code="label.device.type"/></td>
                            <td class="table-header" style="width: 15%;"><spring:message
                                    code="label.device.model"/></td>
                            <td class="table-header" style="width: 30%;"><spring:message
                                    code="label.tenant.oee.calculation.formula"/></td>
                            <%--<td class="table-header" style="width: 20%;"><spring:message code="label.tenant.device.img"/></td>--%>
                            <td class="table-header" style="width: 20%;border-right: none"><spring:message
                                    code="label.operation"/></td>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                    <div style="width: 100%;padding-top:10px;text-align: center;">
                        <a id="add_MachineNumber" class="hollow-button-green" data-id="MachineNumber_TABLE"
                           href="javascript:;"><spring:message code="label.Add"/></a><!--
                        --><a class="hollow-button-green hidden show-or-hidden" data-id="MachineNumber_TABLE"
                              href="javascript:;"
                              onclick="saveMachineNumber(this,'MachineType')"><spring:message code="label.save"/></a>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         data-backdrop="false" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">
                        <spring:message code="label.tenant.set.availability.formula"/>
                    </h4>
                </div>
                <div class="modal-body">
                    <div style="background-color: #fff">
                        <div>
                            <div class="radio" data-value="1">
                                <spring:message code="label.tenant.availability.calculation.formula1"/>
                            </div>
                        </div>
                        <div>
                            <div class="radio" data-value="0">
                                <spring:message code="label.tenant.availability.calculation.formula2"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="cancel" type="button" class="btn btn-default" data-dismiss="modal"><spring:message
                            code="label.cancel"/>
                    </button>
                    <button id="create" type="button" class="btn btn-primary">
                        <spring:message code="label.save"/>
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
    <div class="modal fade" id="IdleModal" tabindex="-1" role="dialog" aria-labelledby="IdleModalLabel"
         data-backdrop="false" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="IdleModalLabel">
                        <spring:message code="label.tenant.edit.idle.reason.template"/>
                    </h4>
                </div>
                <div class="modal-body">
                    <div style="background-color: #fff">
                        <div class="row">
                            <div class="form-group col-sm-12">
                                <label for="reason"><spring:message code="label.tenant.idleReason"/>:</label>
                                <input type="text" id="reason" name="name" class="form-control"/>
                            </div>
                            <div class="form-group col-sm-12">
                                <label for="description"><spring:message code="label.tenant.create.description"/>:</label>
                                <input type="text" id="description" name="cellphone" class="form-control"/>
                            </div>
                            <div class="form-group col-sm-12">
                                <label for="event"><spring:message code="label.tenant.check.event"/>:</label>
                                <select id="event" class="form-control">
                                    <option value=true><spring:message code="label.yes"/></option>
                                    <option value=false><spring:message code="label.no"/></option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="IdleCancel" type="button" class="btn btn-default" data-dismiss="modal"><spring:message
                            code="label.cancel"/>
                    </button>
                    <button id="IdleCreate" type="button" class="btn btn-primary">
                        <spring:message code="label.save"/>
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
    <div class="modal fade" id="FaultModal" tabindex="-1" role="dialog" aria-labelledby="FaultModalLabel"
         data-backdrop="false" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="FaultModalLabel">
                        <spring:message code="label.tenant.edit.fault.reason.template"/>
                    </h4>
                </div>
                <div class="modal-body">
                    <div style="background-color: #fff">
                        <div class="row">
                            <div class="form-group col-sm-12">
                                <label for="reason"><spring:message code="label.tenant.fault.reason"/>:</label>
                                <input type="text" id="FaultTypeReason" name="name" class="form-control"/>
                            </div>
                            <div class="form-group col-sm-12">
                                <label for="description"><spring:message code="label.tenant.create.description"/>:</label>
                                <input type="text" id="FaultTypeDescription" name="cellphone" class="form-control"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="FaultCancel" type="button" class="btn btn-default" data-dismiss="modal"><spring:message
                            code="label.cancel"/>
                    </button>
                    <button id="FaultCreate" type="button" class="btn btn-primary">
                        <spring:message code="label.save"/>
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
    <div class="modal fade" id="MachineModal" tabindex="-1" role="dialog" aria-labelledby="MachineModalLabel" data-backdrop="false" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="MachineModalLabel">
                        <spring:message code="label.tenant.edit.device.typeAndModel.template"/>
                    </h4>
                </div>
                <div class="modal-body">
                    <div style="background-color: #fff">
                        <div class="row">
                            <div class="form-group col-sm-12">
                                <label for="reason"><spring:message code="label.device.type"/>:</label>
                                <input type="text" id="MachineType" name="name" class="form-control"/>
                            </div>
                            <div class="form-group col-sm-12">
                                <label for="description"><spring:message code="label.device.model"/>:</label>
                                <input type="text" id="MachineNumber" name="cellphone" class="form-control"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="MachineCancel" type="button" class="btn btn-default" data-dismiss="modal"><spring:message
                            code="label.cancel"/>
                    </button>
                    <button id="MachineCreate" type="button" class="btn btn-primary">
                        <spring:message code="label.save"/>
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
</div>
<jsp:include page="../../include/foot.jsp"/>
<script src="/js/jquery.ui.widget.js"></script>
<script src="/js/jquery.fileupload.js"></script>
<script>
    $(document).ready(function () {
        var metaId;
        $.ajax({
            url: "/partner/{tenant}/api/v1/metadata/metadataList".replace("{tenant}", getKeyByUrl()),
            type: "get",
            success: function (data) {
                var metadataList = data.data;
                $.each(metadataList, function (index, metadata) {
                    if (metadata.metaKey.toString() === "IDLE") {
                        loadIDLEModulePage(metadata, "IDLE_TABLE");
                    } else if (metadata.metaKey.toString() === "FaultType") {
                        loadFaultTypeModulePage(metadata, "FaultType_TABLE")
                    } else if (metadata.metaKey.toString() === "MachineNumber") {
                        loadMachineModulePage(metadata, "MachineNumber_TABLE")
                    } else {
                        loadAvalabilityPape();
                    }
                })
            },
            fail: function () {
                alert("error")
            }
        });

        $("#myModal").on("show.bs.modal", function () {
            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/getSetting".replace("{tenant}", getKeyByUrl()),
                type: "get",
                success: function (data) {
                    var value = data.data.meta_definition;
                    $("[data-value='" + value + "']").addClass("selected")
                },
                error: function (data) {
                    console.log(data);
                }
            });
        });
        $("#IdleModal").on("show.bs.modal", function (e) {
            console.log(e);
            var $click = $(e.relatedTarget);
            metaId = $click.data("metaid");

            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/getOne".replace("{tenant}", getKeyByUrl()),
                type: "get",
                data: {metaId: metaId},
                success: function (data) {
                    var value = JSON.parse(data.data.metaDefinition);
                    $("#reason").val(value.IDLEReason);
                    $("#description").val(value.IDLEDescription);
                    $("#event option[value=" + value.IDLEEvent + "]").attr("selected", "selected");
                },
                error: function (data) {
                    console.log(data);
                }
            });
        });
        $("#FaultModal").on("show.bs.modal", function (e) {
            console.log(e);
            var $click = $(e.relatedTarget);
            metaId = $click.data("metaid");

            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/getOne".replace("{tenant}", getKeyByUrl()),
                type: "get",
                data: {metaId: metaId},
                success: function (data) {
                    var value = JSON.parse(data.data.metaDefinition);
                    $("#FaultTypeReason").val(value.FaultTypeReason);
                    $("#FaultTypeDescription").val(value.FaultTypeDescription);
                },
                error: function (data) {
                    console.log(data);
                }
            });
        });
        $("#MachineModal").on("show.bs.modal", function (e) {
            console.log(e);
            var $click = $(e.relatedTarget);
            metaId = $click.data("metaid");

            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/getOne".replace("{tenant}", getKeyByUrl()),
                type: "get",
                data: {metaId: metaId},
                success: function (data) {
                    var value = JSON.parse(data.data.metaDefinition);
                    $("#MachineType").val(value.MachineType);
                    $("#MachineNumber").val(value.MachineNumber);
                },
                error: function (data) {
                    console.log(data);
                }
            });
        });

        $(".radio").click(function () {
            $(".selected").removeClass("selected");
            $(this).addClass("selected");
        });

        $("#cancel").click(function () {
            $(".selected").removeClass("selected");
        });

        $("#IdleCreate").click(function () {
            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/updateByMetaId".replace("{tenant}", getKeyByUrl()),
                type: "post",
                contentType:"application/json",
                data: JSON.stringify({
                    metaId:metaId,
                    definition:{
                        IDLEReason: $("#reason").val(),
                        IDLEEvent:$("#event option:selected").val()=="true"?true:false,
                        IDLEDescription: $("#description").val()
                    }
                }),
                success: function () {
                    $("#IdleModal").modal('hide');
                    window.location.reload();
                }
                ,
                error: function (e) {
                    console.log(e);
                }

            })
        });

        $("#FaultCreate").click(function () {
            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/updateByMetaId".replace("{tenant}", getKeyByUrl()),
                type: "post",
                contentType:"application/json",
                data: JSON.stringify({
                    metaId:metaId,
                    definition:{
                        FaultTypeReason: $("#FaultTypeReason").val(),
                        FaultTypeDescription: $("#FaultTypeDescription").val()
                    }
                }),
                success: function () {
                    $("#FaultModal").modal('hide');
                    window.location.reload();
                }
                ,
                error: function (e) {
                    console.log(e);
                }

            })
        });
        $("#MachineCreate").click(function () {
            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/updateByMetaId".replace("{tenant}", getKeyByUrl()),
                type: "post",
                contentType:"application/json",
                data: JSON.stringify({
                    metaId:metaId,
                    definition:{
                        MachineType: $("#MachineType").val(),
                        OOEFormula:"OEE=Availability*Performance*Quality",
                        MachineNumber: $("#MachineNumber").val()
                    }
                }),
                success: function () {
                    $("#MachineModal").modal('hide');
                    window.location.reload();
                }
                ,
                error: function (e) {
                    console.log(e);
                }

            })
        });

        $("#create").click(function () {
            $.ajax({
                url: "/partner/{tenant}/api/v1/metadata/updateSetting".replace("{tenant}", getKeyByUrl()),
                type: "post",
                data: {value: $(".selected").data("value")},
                success: function () {
                    swal({
                        title: "<spring:message code="label.setting.success"/>",
                        text: "",
                        type: "success",
                        showCancelButton: false,
                        showConfirmButton: "true",
                        confirmButtonText: "<spring:message code="label.admin.confirm"/>",
                        cancelButtonText: "",
                        animation: "slide-from-top"
                    }, function () {
                        $(".selected").removeClass("selected");
                        $("#myModal").modal('hide');
                    });
                },
                error: function () {
                    console.log("error")
                }
            });
        });

        $("#add_idle").click(function () {
            var tableSelector = $(this).data("id");
            var newInput = '<tr>' +
                    '<td class="table-body" style="width: 30%;"><input data-key="IDLEReason" style="width: 80%;margin: auto;display: inline;" class="form-control"/></td>' +
                    '<td class="table-body" style="width: 35%;"><input data-key="IDLEDescription" style="width: 80%;margin: auto" class="form-control"/></td>' +
                    '<td class="table-body" style="width: 15%;">' +
                    '   <div class="sie-flex-box" style="line-height: 16px;margin:auto;display: inline-block">' +
                    '     <div class="sie-flex-item item-access" style="margin-right: 0;" onclick="modifyClass(this)">' +
                    '        <i class="sie-checkbox checked" style="margin-right: 0">' +
                    '        </i>' +
                    '     </div>' +
                    '   </div>' +
                    '</td>' +
                    '<td class="table-body sie-btn-group" style="width: 20%;border-right: none">' +
                    '<a href="javascript:;" onclick="deleteTr(this,\'IDLE_TABLE\')"><i class="sie-btn-delete"></i><span><spring:message code="label.user.delete"/></span></a>' +
                    '</td>' +
                    '</tr>';
            if ($("#" + tableSelector).find("tbody").find("tr:last").length === 1) {
                $("#" + tableSelector).find("tbody").find("tr:last").after(newInput);
            } else {
                $("#" + tableSelector).find("tbody").append(newInput);
            }
            var $last_tr = $("#" + tableSelector).find("tr:last");

            $last_tr.after();//追加input
            $(this).next().removeClass("hidden");
            console.log("error" + new Date())
        });

        $("#add_faultType").click(function () {
            var tableSelector = $(this).data("id");
            var newInput = '<tr>' +
                    '<td class="table-body" style="width: 30%;"><input data-key="FaultTypeReason" style="width: 80%;margin: auto" class="form-control"/></td>' +
                    '<td class="table-body" style="width: 50%;"><input data-key="FaultTypeDescription" style="width: 80%;margin: auto" class="form-control"/></td>' +
                    '<td class="table-body sie-btn-group" style="width: 20%;border-right: none">' +
                    '<a href="javascript:;" onclick="deleteTr(this,\'FaultType_TABLE\')"><i class="sie-btn-delete"></i><span><spring:message code="label.user.delete"/></span></a>' +
                    '</td>' +
                    '</tr>';
            if ($("#" + tableSelector).find("tbody").find("tr:last").length === 1) {
                $("#" + tableSelector).find("tbody").find("tr:last").after(newInput);
            } else {
                $("#" + tableSelector).find("tbody").append(newInput);
            }
            $(this).next().removeClass("hidden");
            console.log("error")
        });

        $("#add_MachineNumber").click(function () {
            var tableSelector = $(this).data("id");
            var newInput = '<tr>' +
                    '<td class="table-body" style="width: 15%;"><input data-key="MachineType" style="width: 80%;margin: auto" class="form-control"/></td>' +
                    '<td class="table-body" style="width: 15%;"><input data-key="MachineNumber" style="width: 80%;margin: auto" class="form-control"/></td>' +
                    '<td class="table-body" style="width: 30%;"><input data-key="OOEFormula" style="width: 80%;margin: auto" readonly="readonly" value="OEE=Availability*Performance*Quality" class="form-control"/></td>' +
                    '<td class="table-body sie-btn-group" style="width: 20%;border-right: none">' +
                    '<a href="javascript:;" onclick="deleteTr(this,\'MachineNumber_TABLE\')"><i class="sie-btn-delete"></i><span><spring:message code="label.user.delete"/></span></a>' +
                    '</td>' +
                    '</tr>';
            var $inputFile = $(newInput);
            if ($("#" + tableSelector).find("tbody").find("tr:last").length === 1) {
                $("#" + tableSelector).find("tbody").find("tr:last").after($inputFile);
            } else {
                $("#" + tableSelector).find("tbody").append($inputFile);
            }
            $(this).next().removeClass("hidden");
            console.log("error")
        });
    });

    var loadIDLEModulePage = function (data, selector) {
        var metaDefinition = JSON.parse(data.metaDefinition);
        console.log(metaDefinition);
        var $tr = $("<tr></tr>");
        var event;
        if (metaDefinition.IDLEEvent) {
            event = $("<div></div>").addClass("sie-flex-box").attr("style", "line-height:16px;margin:auto;display:inline-block").append(
                    $("<div></div>").addClass("sie-flex-item item-access item-checked").attr("style", "margin-right:0").append(
                            $("<i></i>").addClass("sie-checkbox checked").attr("style", "margin-right:0")
                    )
            )
        } else {
            event = $("<div></div>").addClass("sie-flex-box").attr("style", "line-height:16px;margin:auto;display:inline-block").append(
                    $("<div></div>").addClass("sie-flex-item item-access").attr("style", "margin-right:0").append(
                            $("<i></i>").addClass("sie-checkbox checked").attr("style", "margin-right:0")
                    )
            )
        }
        $tr.append(
                $("<td></td>").addClass("table-body").attr("style", "width:30%").text(metaDefinition.IDLEReason)).append(
                $("<td></td>").addClass("table-body").attr("style", "width:35%").text(metaDefinition.IDLEDescription)).append(
                $("<td></td>").addClass("table-body").attr("style", "width:15%").append(event)).append(
                $("<td></td>").addClass("table-body sie-btn-group").attr("style", "width:20%;border-right:none").append(
                        $("<a></a>").attr({
                            "data-toggle": "modal",
                            "data-target": "#IdleModal",
                            "style": "cursor: pointer;",
                            "data-metaid": data.metaId
                        }).append(
                                $("<i></i>").addClass("sie-btn-edit")).append(
                                $("<span></span>").text('<spring:message code="label.user.edit"/>'))).append(
                        $("<a></a>").attr("href", "javascript:;").attr("onclick", 'deleteTrData(\'' + data.metaId + '\',this)').append(
                                $("<i></i>").addClass("sie-btn-delete")).append(
                                $("<span></span>").text('<spring:message code="label.user.delete"/>'))
                ));
        $("#" + selector).append($tr);
    };
    var loadFaultTypeModulePage = function (data, selector) {
        var metaDefinition = JSON.parse(data.metaDefinition);
//        console.log(metaDefinition);

        console.log("saveIDLE!");
        var $tr = $("<tr></tr>");
        $tr.append(
                $("<td></td>").addClass("table-body").attr("style", "width:30%").text(metaDefinition.FaultTypeReason)).append(
                $("<td></td>").addClass("table-body").attr("style", "width:15%").text(metaDefinition.FaultTypeDescription)).append(
                $("<td></td>").addClass("table-body sie-btn-group").attr("style", "width:20%;border-right:none").append(
                        $("<a></a>").attr({
                            "data-toggle": "modal",
                            "data-target": "#FaultModal",
                            "style": "cursor: pointer;",
                            "data-metaid": data.metaId
                        }).append(
                                $("<i></i>").addClass("sie-btn-edit")).append(
                                $("<span></span>").text('<spring:message code="label.user.edit"/>'))).append(
                        $("<a></a>").attr("href", "javascript:;").attr("onclick", 'deleteTrData(\'' + data.metaId + '\',this)').append(
                                $("<i></i>").addClass("sie-btn-delete")).append(
                                $("<span></span>").text('<spring:message code="label.user.delete"/>'))
                ));
        $("#" + selector).append($tr);
    };
    var loadMachineModulePage = function (data, selector) {
        var metaDefinition = JSON.parse(data.metaDefinition);
//        console.log(metaDefinition);

        var $tr = $("<tr></tr>");
        $tr.append(
                $("<td></td>").addClass("table-body").attr("style", "width:15%").text(metaDefinition.MachineType)).append(
                $("<td></td>").addClass("table-body").attr("style", "width:15%").text(metaDefinition.MachineNumber)).append(
                $("<td></td>").addClass("table-body").attr("style", "width:30%").text(metaDefinition.OOEFormula)).append(
                $("<td></td>").addClass("table-body sie-btn-group").attr("style", "width:20%;border-right:none").append(
                        $("<a></a>").attr({
                            "data-toggle": "modal",
                            "data-target": "#MachineModal",
                            "style": "cursor: pointer;",
                            "data-metaid": data.metaId
                        }).append(
                                $("<i></i>").addClass("sie-btn-edit")).append(
                                $("<span></span>").text('<spring:message code="label.user.edit"/>'))).append(
                        $("<a></a>").attr("href", "javascript:;").attr("onclick", 'deleteTrData(\'' + data.metaId + '\',this)').append(
                                $("<i></i>").addClass("sie-btn-delete")).append(
                                $("<span></span>").text('<spring:message code="label.user.delete"/>'))).append(

                ));
        $("#" + selector).append($tr);
    };

    function loadAvalabilityPape() {
    }

    var saveIDLE = function (_this, reasonKey) {
        var data = [];
        var tableSelector = $(_this).data("id");
        var trArr = $("#" + tableSelector).find("tr");
        buildData(trArr, reasonKey, data);
        console.log(data);
        $.ajax({
            url: "/partner/{tenant}/api/v1/metadata/addIDLE".replace("{tenant}", getKeyByUrl()),
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(data),
            success: function () {
                $(_this).addClass("hidden");//隐藏保存按钮
                console.log("saveIDLE success!");
                $("#" + tableSelector).find("tbody").html("");
                reloadByKey("IDLE", tableSelector, eachForList);
            },
            fail: function (e) {
                console.log(e);
            }
        });
    };

    var saveFaultType = function (_this, reasonKey) {
        var data = [];
        var tableSelector = $(_this).data("id");
        var trArr = $("#" + tableSelector).find("tr");
        buildData(trArr, reasonKey, data);
        console.log(data);
        $.ajax({
            url: "/partner/{tenant}/api/v1/metadata/addFaultType".replace("{tenant}", getKeyByUrl()),
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(data),
            success: function () {
                $(_this).addClass("hidden");//隐藏保存按钮
                $("#" + tableSelector).find("tbody").html("");
                reloadByKey("FaultType", tableSelector, eachForList);
            },
            fail: function (e) {
                console.log(e);
            }
        });
    };
    var saveMachineNumber = function (_this, reasonKey) {
        var data = [];
        var tableSelector = $(_this).data("id");
        var trArr = $("#" + tableSelector).find("tr");
        buildData(trArr, reasonKey, data);
        console.log(data);
        $.ajax({
            url: "/partner/{tenant}/api/v1/metadata/MachineNumber".replace("{tenant}", getKeyByUrl()),
            type: "post",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(data),
            success: function () {
                $(_this).addClass("hidden");//隐藏保存按钮
                $("#" + tableSelector).find("tbody").html("");
                reloadByKey("MachineNumber", tableSelector, eachForList);
            },
            fail: function (e) {
                console.log(e);
            }
        });
    };

    function reloadByKey(key, tableSelector, callback) {
        console.log("reloadKey");
        $.ajax({
            url: "/partner/{tenant}/api/v1/metadata/metadatas".replace("{tenant}", getKeyByUrl()),
            type: "get",
            data: {key: key},
            success: function (data) {
                console.log("reloadKey  success");
                callback(data.data, key, tableSelector);
            },
            fail: function (e) {
                console.log(e);
            }
        });
    }

    function eachForList(data, key, tableSelector) {
        console.log("eachforlist");
        $.each(data, function (index, definition) {
            if (key === "IDLE") {
                loadIDLEModulePage(definition, tableSelector);
            } else if (key === "FaultType") {
                loadFaultTypeModulePage(definition, tableSelector)
            } else if (key === "MachineNumber") {
                loadMachineModulePage(definition, tableSelector)
            }
        })
    }

    function buildData(trArr, reasonKey, data) {
        $.each(trArr, function (index, tr) {
            var inputArr = $(tr).find("input");
            var IDLE = {};
            if (inputArr.length > 0) {
                for (var i = 0; i < inputArr.length; i++) {
                    var value;
                    var key = $(inputArr[i]).data("key");
                    if (key == "MachineImg") {
                        value = $(inputArr[i]).data("value");
                    } else {
                        value = $(inputArr[i]).val();
                    }
                    if (key === reasonKey || key == "MachineNumber") {
                        if (value === null || value === "" || value === undefined) {
                            return;
                        }
                    }
                    if ((key.indexOf("IDLE") !== -1) && (i == inputArr.length - 1)) {
                        IDLE["IDLEEvent"] = $(tr).find(".item-access").hasClass("item-checked");
                    }
                    IDLE[key] = value == null || value == undefined ? "" : value;
                }
                data.push(IDLE);
                console.log(IDLE);
            }
        });
    }

    var deleteTr = function (_this, selector) {
        _this.parentNode.parentNode.remove();
        if ($("#" + selector).find("input") && $("#" + selector).find("input").length == 0) {
            $("#" + selector).next().find(".show-or-hidden").addClass("hidden");
        }
    };

    var deleteTrData = function (metadataId, _this) {
        console.log(_this);
        $.ajax({
            url: "/partner/{tenant}/api/v1/metadata/delete".replace("{tenant}", getKeyByUrl()),
            type: "post",
            data: {metadataId: metadataId},
            success: function () {
                _this.parentNode.parentNode.remove();
            },
            fail: function (e) {
                console.log(e)
            }
        })
    };

    function updateClick(_this) {
        return $(_this).prev().click();
    }

    function modifyClass(_this) {
        $(_this).hasClass('item-checked') ? $(_this).removeClass('item-checked') : $(_this).addClass('item-checked');
    }
</script>
